package com.duam.porky.tasks;

import static com.duam.porky.ConstantesPorky.URL_PORKY;
import static com.duam.porky.ConstantesPorky.WS_FIELD_SEPARATOR;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.util.Log;

import com.duam.porky.model.Concepto;
import com.duam.porky.model.Usuario;
import com.github.kevinsawicki.http.HttpRequest;

public class DownloadConceptosTask extends AsyncTask<Usuario, Integer, List<Concepto>> 
{

	@Override
	protected List<Concepto> doInBackground(Usuario... params) 
	{
		Usuario usuario = params[0];
		List<Concepto> conceptos = new ArrayList<Concepto>();
		String url = URL_PORKY +"/ws/conceptos?username="+ usuario.getNombreUsuario();
		
		Log.d(DownloadConceptosTask.class.getName(), "Consultado "+ url);
		
		// https://github.com/kevinsawicki/http-request
		String[] lines = HttpRequest.get(url).body().split("\n");
		
		for (String line : lines)
		{
			Log.d(getClass().getName(), "Parseando ["+ line +"]");
			
			if (line.trim().length() > 0)
			{
				String[] valores = line.split(WS_FIELD_SEPARATOR.replaceAll("\\|", "\\\\|"));
				conceptos.add(new Concepto(Integer.valueOf(valores[0]), usuario.getId(), valores[1], 0));
			}
		}		
		
		return conceptos;
	}

}
